package com.health.service.impl;

import com.health.dao.DailyRecordMapper;
import com.health.dao.HealthIndicatorMapper;
import com.health.dao.UserMapper;
import com.health.pojo.domain.DailyRecordDO;
import com.health.pojo.domain.HealthIndicatorDO;
import com.health.pojo.dto.DailyRecordDTO;
import com.health.pojo.dto.HealthIndicatorDTO;
import com.health.pojo.query.UserQuery;
import com.health.pojo.vo.PageResult;
import com.health.service.HealthService;
import java.lang.Boolean;
import java.lang.Override;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.health.exception.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.Map;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.health.constant.ResultCodeConstant;
import java.util.Date;

/**
 * 健康数据管理的实现
 *
 * @author WUYU_MIN
 * @date 2025-04-29 23:51:18
 */
@Service
public class HealthServiceImpl implements HealthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HealthIndicatorMapper healthIndicatorMapper;

    @Autowired
    private DailyRecordMapper dailyRecordMapper;

    @Override
    public Boolean addHealthIndicator(HealthIndicatorDTO healthIndicatorDTO) {
        // 验证用户信息是否存在
        if (userMapper.selectById(healthIndicatorDTO.getUserId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 构建DO对象并保存到数据库
        HealthIndicatorDO healthIndicatorDO = new HealthIndicatorDO();
        healthIndicatorDO.setUserId(healthIndicatorDTO.getUserId());
        healthIndicatorDO.setHeight(healthIndicatorDTO.getHeight());
        healthIndicatorDO.setWeight(healthIndicatorDTO.getWeight());
        healthIndicatorDO.setBloodPressure(healthIndicatorDTO.getBloodPressure());
        healthIndicatorDO.setBloodGlucose(healthIndicatorDTO.getBloodGlucose());
        healthIndicatorDO.setBloodOxygen(healthIndicatorDTO.getBloodOxygen());
        healthIndicatorDO.setHeartRate(healthIndicatorDTO.getHeartRate());
        healthIndicatorDO.setCreatedAt(new Date());
        healthIndicatorDO.setUpdatedAt(new Date());
        int result = healthIndicatorMapper.insert(healthIndicatorDO);
        return result > 0;
    }

    @Override
    public Boolean deleteHealthIndicator(HealthIndicatorDTO healthIndicatorDTO) {
        // 验证指标信息是否存在
        if (healthIndicatorMapper.selectById(healthIndicatorDTO.getIndicatorId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 删除指标信息
        int result = healthIndicatorMapper.deleteById(healthIndicatorDTO.getIndicatorId());
        return result > 0;
    }

    @Override
    public Boolean updateHealthIndicator(HealthIndicatorDTO healthIndicatorDTO) {
        // 验证指标信息是否存在
        if (healthIndicatorMapper.selectById(healthIndicatorDTO.getIndicatorId()) == null) {
            System.out.println("信息否存在" + healthIndicatorDTO.getIndicatorId());
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 构建DO对象并更新到数据库
        HealthIndicatorDO healthIndicatorDO = new HealthIndicatorDO();
        healthIndicatorDO.setUserId(healthIndicatorDTO.getUserId());
        healthIndicatorDO.setHeight(healthIndicatorDTO.getHeight());
        healthIndicatorDO.setWeight(healthIndicatorDTO.getWeight());
        healthIndicatorDO.setBloodPressure(healthIndicatorDTO.getBloodPressure());
        healthIndicatorDO.setBloodGlucose(healthIndicatorDTO.getBloodGlucose());
        healthIndicatorDO.setBloodOxygen(healthIndicatorDTO.getBloodOxygen());
        healthIndicatorDO.setHeartRate(healthIndicatorDTO.getHeartRate());
        healthIndicatorDO.setUpdatedAt(new Date());
        int result = healthIndicatorMapper.updateById(healthIndicatorDO);
        return result > 0;
    }

    @Override
    public PageResult<HealthIndicatorDO> queryHealthIndicator(UserQuery userQuery) {
        // 验证用户信息是否存在
        if (userMapper.selectById(userQuery.getUserId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 按照指定的时间范围和用户ID进行检索
        QueryWrapper<HealthIndicatorDO> queryWrapper = Wrappers.query();
        queryWrapper.eq("user_id", userQuery.getUserId()).ge("created_at", userQuery.getStartDate()).le("created_at", userQuery.getEndDate()).orderByAsc("created_at");
        // 分页查询
        IPage<HealthIndicatorDO> page = new Page<>(userQuery.getPageIndex(), userQuery.getPageSize());
        IPage<HealthIndicatorDO> indicatorPage = healthIndicatorMapper.selectPage(page, queryWrapper);
        PageResult<HealthIndicatorDO> pageResult = new PageResult<>(
                indicatorPage.getTotal(),     // 总记录数（long）→ totalRecords
                page.getCurrent(),            // 当前页码（long）→ pageIndex
                page.getSize(),               // 每页大小（long）→ pageSize
                indicatorPage.getRecords()    // 实际数据集合（List）→ records
        );
        return pageResult;
    }

    @Override
    public Boolean addDailyRecord(DailyRecordDTO dailyRecordDTO) {
        // 验证用户信息是否存在
        if (userMapper.selectById(dailyRecordDTO.getUserId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 构建DO对象并保存到数据库
        DailyRecordDO dailyRecordDO = new DailyRecordDO();
        dailyRecordDO.setUserId(dailyRecordDTO.getUserId());
        dailyRecordDO.setSteps(dailyRecordDTO.getSteps());
        dailyRecordDO.setSleepDuration(dailyRecordDTO.getSleepDuration());
        dailyRecordDO.setWaterIntake(dailyRecordDTO.getWaterIntake());
        dailyRecordDO.setRecordDate(dailyRecordDTO.getRecordDate());
        dailyRecordDO.setCreatedAt(new Date());
        dailyRecordDO.setUpdatedAt(new Date());
        int result = dailyRecordMapper.insert(dailyRecordDO);
        return result > 0;
    }

    @Override
    public Boolean deleteDailyRecord(DailyRecordDTO dailyRecordDTO) {
        // 验证记录信息是否存在
        if (dailyRecordMapper.selectById(dailyRecordDTO.getRecordId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 删除记录信息
        int result = dailyRecordMapper.deleteById(dailyRecordDTO.getRecordId());
        return result > 0;
    }

    @Override
    public Boolean updateDailyRecord(DailyRecordDTO dailyRecordDTO) {
        // 验证记录信息是否存在
        if (dailyRecordMapper.selectById(dailyRecordDTO.getRecordId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 构建DO对象并更新到数据库
        DailyRecordDO dailyRecordDO = new DailyRecordDO();
        dailyRecordDO.setRecordId(dailyRecordDTO.getRecordId());
        dailyRecordDO.setUserId(dailyRecordDTO.getUserId());
        dailyRecordDO.setSteps(dailyRecordDTO.getSteps());
        dailyRecordDO.setSleepDuration(dailyRecordDTO.getSleepDuration());
        dailyRecordDO.setWaterIntake(dailyRecordDTO.getWaterIntake());
        dailyRecordDO.setRecordDate(dailyRecordDTO.getRecordDate());
        dailyRecordDO.setUpdatedAt(new Date());
        int result = dailyRecordMapper.updateById(dailyRecordDO);
        return result > 0;
    }

    @Override
    public PageResult<DailyRecordDO> queryDailyRecord(UserQuery userQuery) {
        // 验证用户信息是否存在
        if (userMapper.selectById(userQuery.getUserId()) == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 按照指定的时间范围和用户ID进行检索
        QueryWrapper<DailyRecordDO> queryWrapper = Wrappers.query();
        queryWrapper.eq("user_id", userQuery.getUserId())
                    .ge("record_date", userQuery.getStartDate())
                    .le("record_date", userQuery.getEndDate())
                    .orderByAsc("record_date");
        // 分页查询
        IPage<DailyRecordDO> page = new Page<>(userQuery.getPageIndex(), userQuery.getPageSize());
        IPage<DailyRecordDO> recordPage = dailyRecordMapper.selectPage(page, queryWrapper);
        PageResult<DailyRecordDO> pageResult = new PageResult<>(
                recordPage.getTotal(),     // totalRecords
                page.getCurrent(),         // pageIndex
                page.getSize(),            // pageSize
                recordPage.getRecords()    // records
        );
        return pageResult;
    }
}
